package cn.com.pajx.pajx_smart_platform.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import androidx.annotation.Nullable;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.com.pajx.pajx_smart_platform.bean.EventMessage;
import cn.com.pajx.pajx_smart_platform.tools.AppConstant;
import cn.com.pajx.pajx_smart_platform.tools.LogUtil;


/**
 * Created by ruancw on 2024/9/9.
 * 执行定时任务
 */

public class AlarmService extends Service {

    public static String ACTION_ALARM = "action_alarm";
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private final Intent intent = new Intent("com.pajx.alarm.RECEIVER");
    private boolean isSendBroadcast = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //启动定时任务
        startAlarmTask();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 启动定时任务管理器执行定时
     */
    @SuppressLint("ScheduleExactAlarm")
    private void startAlarmTask() {
        //解决定时任务首次加载数据的问题，第一次默认不加载
        if (isSendBroadcast) {
            mHandler.post(() -> EventBus.getDefault().post(new EventMessage(AppConstant.ALARM_TASK, getCurrentYMDHMS())));
        }

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(this, AlarmService.class);
        alarmIntent.setAction(AlarmService.ACTION_ALARM);
        @SuppressLint("UnspecifiedImmutableFlag")
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            flags |= PendingIntent.FLAG_IMMUTABLE;
        }
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, alarmIntent, flags);
        LogUtil.e("alarm_task_start=" + getCurrentYMDHMS());
        isSendBroadcast = true;

        //设置周期为30分钟
        assert am != null;
        int MINUTE = 60 * 60 * 1000;//间隔30分钟
        am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + MINUTE, pendingIntent);
    }

    public static String getCurrentYMDHMS() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.format(new Date(System.currentTimeMillis()));
    }

}
